using System;
using System.Drawing;
using System.Linq;

namespace OpenWaves
{
    public partial class CharacterWidth
    {
        public readonly static ICharacterWidthStatisticsProvider Proportional = new ProprotionalWidthStatistics();

        private class ProprotionalWidthStatistics : ICharacterWidthStatisticsProvider
        {
            protected static double[] CalculateWidthStatistics(Font font)
            {
                var widths = new double[127];

                var g = Graphics.FromImage(new Bitmap(1, 1));
                for (int i = 32; i < 127; i++)
                {
                    widths[i] = g.MeasureString(Char.ConvertFromUtf32(i), font, 100).Width;
                }

                var avgLetterWidth = Enumerable.Range(65, 26).Concat(Enumerable.Range(97, 26)).Select(i => widths[i]).Average();

                for (int i = 0; i < widths.Length; i++)
                {
                    widths[i] = widths[i] / avgLetterWidth;
                }

                return widths;
            }

            private static readonly double[] characterWidths = CalculateWidthStatistics(new Font("Arial", 1));

            public double GetCharacterWidth(char ch)
            {
                if (ch < characterWidths.Length)
                    return characterWidths[ch];
                else
                    return 1;
            }
        }
    }
}
